﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace LogServices
{
    public class LogService
    {
        private static string GetAssemblyPath()
        {
            string l = System.Reflection.Assembly.GetEntryAssembly().Location;

            FileInfo fi = new FileInfo(l);
            return fi.DirectoryName;
        }
        private LogService()
        {
            var path = Path.Combine(GetAssemblyPath(), "log");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            sw = new StreamWriter(Path.Combine(path, "log.log"), true, Encoding.UTF8);
            sw.AutoFlush = true;
            initTime = DateTime.Now;
        }
        StreamWriter sw;
        DateTime initTime;
        static Lazy<LogService> _log = new Lazy<LogService>(() =>
        {
            return new LogService();
        });

        public static LogService Instance { get { return _log.Value; } }

        public void Write(Exception ex)
        {
            this.WriteInternal(ex.ToString());
        }
        public void Write(object objMsg)
        {
            if (objMsg == null)
                return;
            this.WriteInternal(objMsg.ToString());
        }

        void WriteInternal(string msg)
        {
            //if (sw == null)
            //    return;
            lock (sw)
            {
                if (initTime.Day != DateTime.Now.Day)
                {
                    sw.BaseStream.Seek(0, SeekOrigin.Begin);
                    sw.BaseStream.SetLength(0);
                }
                sw.WriteLine(string.Format("{0}：{1}", DateTime.Now.ToString(), msg));
            }
        }
    }
}
